import axios from 'axios'
import useAdminStore from '@/store'
import pinia from '@/store/store'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'

const request = axios.create({
	baseURL: import.meta.env.VITE_APP_BASEURL,
	timeout: 99999,
	headers: { 'Content-Type': 'application/json' },
})

request.interceptors.request.use(
	(config) => {
		const admin = useAdminStore(pinia)
		admin.loading = true
		admin.loadingCount++
		if (sessionStorage.getItem('token')) {
			config.headers['x-token'] = sessionStorage.getItem('token')
		}
		return config
	},
	(error) => {
		const admin = useAdminStore(pinia)
		admin.loading = false
		admin.loadingCount = 0
		return Promise.reject(error)
	},
)

request.interceptors.response.use(
	(response) => {
		const admin = useAdminStore(pinia)

		admin.loadingCount--
		if (admin.loadingCount < 1) {
			admin.loading = false
			admin.loadingCount = 0
		}
		const res = response.data
		if (res.code && res.code !== 0) {
			if (res.code === 401) {
				sessionStorage.clear()
				ElMessageBox.alert('登录过期，请重新登录', '提示').then(() => {
					window.location.href = '/'
				})
			}
			ElMessage.error(res.msg)
			return Promise.reject(res.msg)
		} else {
			return response.data.data
		}
	},
	(error) => {
		const admin = useAdminStore(pinia)

		admin.loading = false
		admin.loadingCount = 0
		if (error.message.includes('timeout')) {
			ElMessage.error('网络超时')
		} else if (error.message === 'Network Error') {
			ElMessage.error('网络连接错误')
		} else if (error.response.status === 401) {
			sessionStorage.clear()
			ElMessageBox.alert('登录过期，请重新登录', '提示').then(() => {
				window.location.href = '/'
			})
		} else {
			if (error.response.data) ElMessage.error(error.response.statusText)
			else ElMessage.error('接口路径找不到')
		}
		return Promise.reject(error)
	},
)

export default request
